from jinja2 import Template
import json
import os
import shutil


def gen_web_config(client_config, gen_path):
    web_config = client_config["web"]
    # 读取模板文件
    config_path = os.path.join(os.path.dirname(__file__), "webconfig.template")

    with open(config_path, 'r', encoding='utf-8') as f:
        template_content = f.read()

    # 使用 Jinja2 渲染模板
    template = Template(template_content)
    rendered_content = template.render(**web_config)

    # 将生成的内容写入 webconfig.js
    config_path = f'{gen_path}/webconfig.js'
    with open(config_path, 'w', encoding='utf-8') as f:
        f.write(rendered_content)


def gen_client_config(client_config, gen_path, index_str):
    config = client_config["config"]
    config["serverPort"] = client_config["port"]
    if index_str:
        config["index"] = '_' + index_str
    # 读取模板文件
    config_path = os.path.join(os.path.dirname(__file__), "client_config.template")
    with open(config_path, 'r', encoding='utf-8') as f:
        template_content = f.read()

    # 使用 Jinja2 渲染模板
    template = Template(template_content)
    rendered_content = template.render(**config)

    # 将生成的内容写入 client_config.py
    config_path = f'{gen_path}/client_config.py'
    with open(config_path, 'w', encoding='utf-8') as f:
        f.write(rendered_content)


def cp_files(gen_path, client_dir):
    project_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
    raw_client_path = os.path.join(project_path, "client")
    target_client_path = os.path.join(project_path, client_dir)
    if client_dir != "client":
        if os.path.exists(target_client_path):
            shutil.rmtree(target_client_path)
        shutil.copytree(raw_client_path, target_client_path)
    shutil.copy(gen_path + "/webconfig.js", target_client_path + "/dist/webconfig.js")
    shutil.copy(gen_path + "/client_config.py", target_client_path + "/client_config.py")
    shutil.rmtree(gen_path)


def clean_files(client_dir, gen_path):
    project_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
    target_client_path = os.path.join(project_path, client_dir)
    print(">>> only clean: ", target_client_path)
    if client_dir != "client":
        if os.path.exists(target_client_path):
            shutil.rmtree(target_client_path)
    if os.path.exists(gen_path):
        shutil.rmtree(gen_path)

def gen_config_file(only_clean=False):
    config_path = os.path.join(os.path.dirname(__file__), "client_instances_config.json")
    with open(config_path, "r") as f:
        content = f.read()
    config = json.loads(content)
    for key, value in config.items():
        if not key.startswith("client"):
            continue
        idx = 0
        if '_' in key:
            idx = int(key.split('_')[1])
        index_str = str(idx if idx != 0 else "")
        client_dir = f'client{idx if idx != 0 else ""}'
        gen_path = os.path.join(os.path.dirname(__file__), client_dir)
        if not os.path.exists(gen_path):
            os.makedirs(gen_path)
        print("--- load config: ", key, value)
        if only_clean:
            clean_files(client_dir, gen_path)
        else:
            print("gen: ", gen_path)
            gen_client_config(value, gen_path, index_str)
            gen_web_config(value, gen_path)
            cp_files(gen_path, client_dir)


if __name__ == '__main__':
    only_clean = False
    import sys

    if len(sys.argv) > 1:
        only_clean = sys.argv[1] != ""
    gen_config_file(only_clean)
